package com.lingyuan.auth.service;

import com.alibaba.fastjson.JSON;
import com.lingyuan.auth.fegin.UmsRemoteService;
import com.lingyuan.auth.form.LoginBody;
import com.lingyuan.common.core.constant.CacheConstants;
import com.lingyuan.common.core.constant.Constants;
import com.lingyuan.common.core.constant.SecurityConstants;
import com.lingyuan.common.core.constant.UserConstants;
import com.lingyuan.common.core.domain.R;
import com.lingyuan.common.core.domain.vo.ums.MemberLogin;
import com.lingyuan.common.core.domain.vo.ums.MemberVo;
import com.lingyuan.common.core.enums.UserStatus;
import com.lingyuan.common.core.exception.ServiceException;
import com.lingyuan.common.core.text.Convert;
import com.lingyuan.common.core.utils.DateUtils;
import com.lingyuan.common.core.utils.JwtUtils;
import com.lingyuan.common.core.utils.StringUtils;
import com.lingyuan.common.core.utils.ip.IpUtils;
import com.lingyuan.common.redis.service.RedisService;
import com.lingyuan.common.security.utils.SecurityUtils;
import com.lingyuan.system.api.RemoteUserService;
import com.lingyuan.system.api.domain.SysUser;
import com.lingyuan.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.UUID;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class UmsLoginService
{
    @Autowired
    private UmsRemoteService umsRemoteService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 登录
     */
    public MemberLogin login(LoginBody loginBody) {
        R<MemberVo> byUserName = umsRemoteService.findByUserName(loginBody.getUsername());
        if (byUserName.getCode() != 200){
            throw new ServiceException(byUserName.getMsg());
        }
        MemberVo data = byUserName.getData();
        if (data == null){
            throw new ServiceException("用户名或密码错误");
        }
        if (!data.getPassword().equals(loginBody.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        String userKey = UUID.randomUUID().toString();
        String token = JwtUtils.createToken(new HashMap<String, Object>() {{
            put("user_key",userKey );
        }});
        stringRedisTemplate.opsForValue().set(CacheConstants.LOGIN_TOKEN_KEY + userKey, JSON.toJSONString(data), 15, java.util.concurrent.TimeUnit.MINUTES);
        return new MemberLogin(token,"15MIN");
    }
}
